package com.arlen.security_oauth2_1.service;

import com.arlen.security_oauth2_1.mapper.LoginMapper;
import com.arlen.security_oauth2_1.pojo.PageCodeEnum;
import com.arlen.security_oauth2_1.pojo.Po_User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import sun.net.www.http.HttpClient;

import javax.swing.text.html.Option;
import javax.xml.ws.spi.http.HttpContext;
import java.util.Optional;
import java.util.zip.DataFormatException;

@SuppressWarnings("all")
@Service
public class LoginService implements UserDetailsService {

    @Autowired
    LoginMapper loginMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        LambdaQueryWrapper<Po_User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Po_User::getUserName,s);
        Po_User po_user = loginMapper.selectOne(lambdaQueryWrapper);

        Optional<Po_User> optionalPo_user = Optional.ofNullable(po_user);
        if (!optionalPo_user.isPresent()){
            throw new UsernameNotFoundException(PageCodeEnum.LOGIN_FAIL.getMsg()+System.currentTimeMillis());
        }

        return new User(po_user.getUserName(),po_user.getPassWord(), AuthorityUtils.commaSeparatedStringToAuthorityList(po_user.getAuth()));

    }
}
